/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.taobao.dingtalk.service.message;

import com.alibaba.fastjson.JSONObject;
import com.taobao.dingtalk.common.DingTalkErrorConstants;
import com.taobao.dingtalk.common.DingTalkResponse;
import com.taobao.dingtalk.model.message.DingMessage;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Base64;

/***
 * 企业自定义机器人消息推送
 * @since:dingtalk-api 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2020/03/17 13:01
 */
public class DingTalkRebotMessageService {

    Logger logger= LoggerFactory.getLogger(DingTalkRebotMessageService.class);
    /**
     * 接收机器人消息推送的地址
     */
    private final String accessTokenurl;
    /**
     * 机器人签名秘钥
     */
    private final String secret;

    public DingTalkRebotMessageService(String accessTokenurl, String secret) {
        this.accessTokenurl = accessTokenurl;
        this.secret = secret;
    }

    /**
     * 推送机器人消息
     * https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
     * @param dingMessage
     * @return
     */
    public DingTalkResponse sendTextMessage(DingMessage dingMessage){
        DingTalkResponse dingTalkResponse=new DingTalkResponse();
        StringBuffer rebotUrl=new StringBuffer(accessTokenurl);
        try {
            String timestamp=String.valueOf(System.currentTimeMillis());
            //签名
            String strToSign=timestamp+"\n"+secret;
            Mac mac=Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(strToSign.getBytes("UTF-8"));
            String sign= URLEncoder.encode(new String(Base64.getEncoder().encode(signData)),"UTF-8");
            logger.info("sign:{},timestamp:{}",sign,timestamp);
            rebotUrl.append("&timestamp=").append(timestamp).append("&sign=").append(sign);
            CloseableHttpClient client= HttpClients.createDefault();
            HttpPost post=new HttpPost(rebotUrl.toString());
            post.addHeader("Content-Type","application/json");
            post.setEntity(new StringEntity(dingMessage.toString(),"UTF-8"));
            CloseableHttpResponse response=client.execute(post);
            if (response!=null&&response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                logger.info("发送请求成功");
                String resp= EntityUtils.toString(response.getEntity(),"UTF-8");
                logger.info(resp);
                JSONObject jsonObject=JSONObject.parseObject(resp);
                long code=jsonObject.getLong("errcode");
                String msg=jsonObject.getString("errmsg");
                dingTalkResponse.setErrMsg(msg);
                dingTalkResponse.setErrorCode(String.valueOf(code));
                dingTalkResponse.setSuccess(code== DingTalkErrorConstants.ERROR_CODE_SUCCESS);
                if (code== DingTalkErrorConstants.ERROR_CODE_BUSY){
                    //业务繁忙,重试
                    logger.error("服务器繁忙,推送工作消息失败,重试1次");
                }
            }
        } catch (Exception e) {
            logger.error("推送机器人消息失败,错误信息:{}",e.getMessage());
            logger.info(e.getMessage(),e);
        }
        return dingTalkResponse;

    }


}
